package com.cradom.event.realm;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.cradom.event.model.Account;
import com.cradom.event.service.AccountService;
import com.cradom.event.service.AuthorityService;

public class MyRealm extends AuthorizingRealm{

	@Resource
	private AuthorityService authorityService;
	
	@Resource
	private AccountService accountService;
	
	//授权
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String phone = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setRoles(authorityService.getRoleContentByPhone(phone));
		return info;
	}

	//认证
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException{
		String phone = (String) token.getPrincipal();
		Account account=accountService.findAccountByPhone(phone);
		if (account != null) {
			AuthenticationInfo info = null;
			info = new SimpleAuthenticationInfo(account.getPhone(), account.getPassword(), "jdbcRealm");
			return info;
		} else {
			return null;
		}
	}

}
